<?php

namespace App\Http\Controllers\Admin\Framework\Common;

use App\Http\Controllers\Admin\ParentController;
use App\Master\Framework\Extend\DataUtil;
use App\Master\Framework\Library\Uploads;
use App\Models\Admin\Framework\AdminGalleryGroupModel;
use App\Models\Admin\Framework\AdminGalleryModel;
use App\Utils\AppResult;
use Illuminate\Http\Request;

class GalleryController extends ParentController
{

    public function __construct(array $attributes = [])
    {
        parent::__construct();
    }

    public function iframe(Request $request)
    {
        $params = $request->all();
        if ($request->isMethod('post')) {
            $gallery = AdminGalleryModel::query()->select(['id', 'group_id', 'original', 'url', 'active', 'type', 'size'])->where('status', 1);
            if (!empty($params['keyword'])) {
                $gallery->where('original', 'like', "%{$params['keyword']}%");
            }
            if (!empty($params['group_id'])) {
                $gallery->where('group_id', intval($params['group_id']));
            }
            if (!empty($params['type'])) {
                $gallery->where('type', 'like', $params['type']);
            }
            $res = $gallery->orderBy('id', 'desc')->paginate($params['size'] ?? 12);

            return AppResult::response200('success', $res);
        } else {
            $ft = $params['ft'] ?? '1';
            return view('admin.framework.common.gallery.iframe', [
                'ft' => $ft,
                'mx' => $params['mx'] ?? '1',
                'dr' => $params['dr'] ?? '',
                'se' => $params['se'] ?? '10',
                'ck' => $params['ck'] ?? '',
                'sx' => $params['sx'] ?? (Uploads::$_fileTypeExt[$ft] ?? ''),
            ]);
        }
    }

    public function insert(Request $request)
    {
        /*获取上传文件流*/
        if (!$file = $request->input('url')) {
            return AppResult::response201('文件保存失败！ERR:url');
        }
        if (!$key = $request->input('key')) {
            return AppResult::response201('文件保存失败！ERR:key');
        }
        if ((empty($request->driver) || ($request->driver != 'oss' && $request->driver != 'cos')) && !$disk = Uploads::disksQiNiu()) {
            return AppResult::response201('文件保存失败！ERR:driver');
        }

//        $size = $disk->size((string)($request->hash ?? ''));
        if ((empty($request->driver) || ($request->driver != 'oss' && $request->driver != 'cos'))) {
            $size = $disk->size((string)$key);
        }else{
            $size = $request->size ?? 0;
        }

        $file_name           = $request->input('file_name');
        $ext                 = explode('.', $file_name);
        $ext                 = end($ext);
        $gallery             = new AdminGalleryModel();
        $gallery->type       = $request->input('type');
        $gallery->group_id   = $request->input('group_id');
        $gallery->original   = $file_name ?: $key;
        $gallery->name       = (string)($request->hash ?? '');
        $gallery->url        = $file;
        $gallery->size       = (int) $size;
        $gallery->ext        = $ext;
        $gallery->status     = 1;
        $gallery->created_at = time();
        $gallery->save();
        return AppResult::response200('success！', $gallery->url);
    }

    public function upload(Request $request)
    {
        /*获取上传文件流*/
        if (!$file = $request->file('file')) {
            return AppResult::response201('请上传文件！');
        }
        if (!$file->isValid()) {
            return AppResult::response201('文件上传失败！');
        }
        $size     = $request->size ? intval($request->input('size')) : 20;
        $type     = $request->type ? intval($request->input('type')) : 1;
        $group_id = $request->group_id ? intval($request->input('group_id')) : 1;
        $res      = (Uploads::getInstance('image', ['size' => $size, 'dir' => '', 'type' => $type]))->init('file')->getMessage();
        if ($res['code'] !== 200) {
            return AppResult::response201($res['msg']);
        }

        $gallery             = new AdminGalleryModel();
        $gallery->type       = $type;
        $gallery->group_id   = $group_id ? intval($group_id) : 1;
        $gallery->original   = $res['data']['file_name'];
        $gallery->name       = $res['data']['name'];
        $gallery->url        = $res['data']['url'];
        $gallery->size       = $res['data']['file_size'];
        $gallery->ext        = $res['data']['file_ext'];
        $gallery->status     = 1;
        $gallery->created_at = time();
        unset($file);
        $gallery->save();

        return AppResult::response200('success', $gallery->url);
    }

    public function remove(Request $request)
    {
        if (empty($request->id) && empty($request->ids)) {
            return AppResult::response201('请选择需要操作的图片！');
        }
        if ($request->move == 'true') {
            $request->gid = $request->gid ? $request->gid : 0;
            if ($request->id) {
                AdminGalleryModel::query()->where('id', $request->id)->update(['gid' => $request->gid]);
            } else {
                $request->ids = DataUtil::stringToArray($request->ids);
                AdminGalleryModel::query()->whereIn('id', $request->ids)->update(['gid' => $request->gid]);
            }
        } else {
            if ($request->id) {
                AdminGalleryModel::query()->where('id', $request->id)->delete();
            } else {
                $request->ids = DataUtil::stringToArray($request->ids);
                AdminGalleryModel::query()->whereIn('id', $request->ids)->delete();
            }
        }
        return AppResult::response200('图片操作成功！');
    }

    public function original(Request $request)
    {
        if(!$request->id)
        {
            return AppResult::response200('请选择需要操作的文件！');
        }
        if(!$request->name)
        {
            return AppResult::response200('请添加文件名！');
        }
        if(!AdminGalleryModel::query()->where('id', $request->id)->exists())
        {
            return AppResult::response200('文件不存在！');
        }
        AdminGalleryModel::query()->where('id', $request->id)->update([
            'original' => $request->name
        ]);
        return AppResult::response200('操作成功！');
    }

    public function group(Request $request)
    {
        $params = $request->all();

        $type          = intval($params['type'] ?? 1);
        $gallery_group = AdminGalleryGroupModel::query()->where('type', $type)->orderBy('id', 'asc')->get()->toArray();
        if ($type === 20) {
            array_unshift($gallery_group, ['id' => 1, 'name' => '系统', 'total' => 0, 'active' => false, 'remove' => false]);
        } else {
            array_unshift($gallery_group, ['id' => 1, 'name' => '未分组', 'total' => 0, 'active' => false, 'remove' => false]);
        }
        array_unshift($gallery_group, ['id' => 0, 'name' => '全部', 'total' => 0, 'active' => true, 'remove' => false]);
        foreach ($gallery_group as $key => $value) {
            $gallery_group[$key]['active'] = false;
            $model                         = AdminGalleryModel::query()->where('status', 1);
            if (!empty($value['id'])) {
                $model->where('group_id', $value['id']);
            }
            if (!empty($params['keyword'])) {
                $model->where('original', 'like', "%{$params['keyword']}%");
            }
            if (!empty($params['type'])) $model->where('type', $params['type']);

            if (($value['id']) > 1) {
                $gallery_group[$key]['remove'] = true;
            }
            $gallery_group[$key]['total'] = $model->count();
        }
        return AppResult::response200('success', $gallery_group);
    }

    /**
     * 创建素材库分组
     * @param Request $request
     * @return string
     */
    public function groupCreate(Request $request)
    {
        if (!($request->name)) {
            return AppResult::response201('请填写名称！');
        }

        $type = $request->type ? $request->type : 1;

        if (AdminGalleryGroupModel::query()->where('type', $type)->count('id') > 4) {
            return AppResult::response201('最多可添加5个！');
        }

        $id = AdminGalleryGroupModel::query()->insertGetId(['name' => $request->name, 'type' => $type]);

        return AppResult::response200('添加成功！', $id);
    }

    /**
     * 修改素材库分组
     * @param Request $request
     * @return string
     */
    public function groupUpdate(Request $request)
    {
        if (!($request->id)) {
            return AppResult::response201('编辑失败，请稍后再试！');
        }
        if (!($request->name)) {
            return AppResult::response201('请填写名称！');
        }

        AdminGalleryGroupModel::query()->where('id', $request->id)->update(['name' => $request->name]);

        return AppResult::response200('编辑成功！');
    }

    /**
     * 素材库分组删除
     * @param Request $request
     * @return string
     */
    public function groupRemove(Request $request)
    {
        if (empty($request->id)) {
            return AppResult::response201('删除失败, 请稍后再试！');
        }

        $type = AdminGalleryGroupModel::query()->where('id', $request->id)->value('type');

        if (!AdminGalleryGroupModel::query()->where('id', $request->id)->delete()) {
            return AppResult::response201('删除失败, 请稍后再试！');
        }

        if ($type == 1) {
            AdminGalleryModel::query()->where('group_id', $request->id)->update(['group_id' => 1]);
        } else {
            AdminGalleryModel::query()->where('group_id', $request->id)->delete();
        }

        return AppResult::response200('分组删除成功！');
    }
}